package com.xunshangwang.pinhaohuo.ui.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.adapters.GroupAdapter;
import com.xunshangwang.pinhaohuo.decorations.DividerItemDecoration;
import com.xunshangwang.pinhaohuo.decorations.OffsetItemDecoration;
import com.xunshangwang.pinhaohuo.entity.Group;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.ui.activities.GroupDetailActivity;
import com.xunshangwang.pinhaohuo.widgets.LMSizeRecyclerView;
import com.xunshangwang.pinhaohuo.widgets.RefreshLayout;

import org.json.JSONObject;

import java.util.List;

import cz.msebera.android.httpclient.Header;
import tool.library.adapter.BaseRecyclerAdapter;
import tool.library.widget.LoadRecyclerView;

/**
 * Created by xzp on 16/2/26.
 */
public class GroupListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,LoadRecyclerView.OnLoadListener,
        BaseRecyclerAdapter.OnItemClickListener{

    private int mStatus;
    private LMSizeRecyclerView mRecycler;
    private RefreshLayout mRefresh;
    private GroupAdapter mAdapter;
    public static GroupListFragment newInstance(int status){
        Bundle bundle=new Bundle();
        bundle.putInt("status", status);
        GroupListFragment fragment=new GroupListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(getArguments()!=null){
            mStatus=getArguments().getInt("status",0);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_group_list,container,false);
        mRecycler= (LMSizeRecyclerView) view.findViewById(R.id.group_list);
        mRecycler.setLayoutManager(new LinearLayoutManager(inflater.getContext()));
        mRecycler.setOnLoadListener(this);
        mRecycler.addItemDecoration(new DividerItemDecoration(inflater.getContext()){
            @Override
            protected boolean canDraw(int position) {
                return position<mAdapter.getItemCount()-1;
            }
        });
        mRecycler.addItemDecoration(new OffsetItemDecoration(inflater.getContext(),R.dimen.group_list_item_offset){
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                if(parent.getChildAdapterPosition(view)<parent.getAdapter().getItemCount()-2)
                    super.getItemOffsets(outRect, view, parent, state);
            }
        });
        mRecycler.setOnLoadListener(this);
        mRefresh= (RefreshLayout) view.findViewById(R.id.refresh_layout);
        mRefresh.setOnRefreshListener(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mAdapter=new GroupAdapter(getContext());
        mAdapter.setOnItemClickListener(this);
        mRecycler.setAdapter(mAdapter);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.setRefreshing(true);
                onRefresh();
            }
        }, 150);
    }

    @Override
    public void onLoad(LoadRecyclerView recyclerView) {
        loadGroupList();
    }

    @Override
    public void onRefresh() {
        refreshGroupList();
    }

    @Override
    public void onItemClick(BaseRecyclerAdapter adapter, View item, int position) {
        Intent intent=new Intent(getContext(), GroupDetailActivity.class);
        intent.putExtra("id",mAdapter.getList().get(position).getGroup_order_id());
        startActivity(intent);
    }

    private void refreshGroupList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=groups");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&offset=0");
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&status="+mStatus);
        HttpTool.get(getContext(), builder.toString(), new JsonHttpHandler<List<Group>>() {
            @Override
            public void onFinish() {
                super.onFinish();
                mRefresh.setRefreshing(false);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Group> response) {
                mAdapter.setList(response);
                mRecycler.loadFinish(response);
            }

            @Override
            public List<Group> parseData(JSONObject object) throws Throwable {
                List<Group> list= JSON.parseArray(object.getString("group_orders"), Group.class);
                if(list!=null) {
                    long currentTime = object.getLong("current_time");
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setCurrent_time(currentTime);
                    }
                }
                return list;
            }
        });
    }
    private void loadGroupList(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Weuser&a=groups");
        builder.append("&token="+getMainApplication().getToken());
        builder.append("&offset="+mAdapter.getList().size());
        builder.append("&size="+LMSizeRecyclerView.SIZE);
        builder.append("&status="+mStatus);
        HttpTool.get(getContext(), builder.toString(), new JsonHttpHandler<List<Group>>() {
            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, List<Group> errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                mRecycler.loadFinish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, List<Group> response) {
                mAdapter.addAll(response);
                mRecycler.loadFinish(response);
            }

            @Override
            public List<Group> parseData(JSONObject object) throws Throwable {
                List<Group> list= JSON.parseArray(object.getString("group_orders"), Group.class);
                if(list!=null) {
                    long currentTime = object.getLong("current_time");
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setCurrent_time(currentTime);
                    }
                }
                return list;
            }
        });
    }
}
